<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'



interface Business {
  id: number
  businessName: string
  image: string
  description: string
  score: number
  deliveryFees: number
  miniDeliveryFee: number
  monthSold: number
}

const router = useRouter()

const businesses = ref<Business[]>([])

// base64 转换为图片URL
const convertBase64ToUrl = (base64String: string) => {
  if (base64String.startsWith('data:image')) {
    return base64String
  }
  return `data:image/png;base64,${base64String}`
}

const getBusinessList = async () => {
  try {
    const response = await fetch('http://localhost:8080/business/list')
    const data = await response.json()
    
    // 使用 Set 记录已存在的商家 ID
    const existingIds = new Set<number>()
    const uniqueBusinesses = data.filter((business: Business) => {
      if (existingIds.has(business.id)) {
        return false
      }
      existingIds.add(business.id)
      return true
    })

    businesses.value = uniqueBusinesses.map((business: Business) => ({
      ...business,
      image: convertBase64ToUrl(business.image)
    }))
  } catch (error) {
    console.error('获取商家列表失败:', error)
  }
}

// 添加跳转方法
const goToBusinessInfo = async (businessId: number) => {
  try {
    // 检查用户是否已登录
    const token = localStorage.getItem('token')
    if (!token) {
      alert('请先登录')
      router.push('/login')
      return
    }
    
    // 修复路由路径，将 {businessId} 改为实际的变量插值
    router.push(`/businessInfo/${businessId}`)

  } catch (error) {
    console.error('切换商家失败:', error)
  }
}

onMounted(() => {
  getBusinessList()
})
</script>

<template>
  <div class="business-list">
    <div v-for="(business, index) in businesses" 
         :key="business.id" 
         class="business-item flex p-4 border-b border-gray-100"
         @click="goToBusinessInfo(business.id)">
      <!-- 商家图片 -->
      <div class="relative w-20 h-20 mr-3">
        <img :src="business.image" 
             :alt="business.businessName"
             class="w-full h-full object-cover rounded">
      </div>
      
      <!-- 商家信息 -->
      <div class="flex-1">
        <h3 class="text-4 font-medium mb-1">{{ business.businessName }}</h3>
        <div class="text-3 text-gray-500 mb-1">{{ business.description }}</div>
        <div class="text-3 text-gray-600">
          <span>¥{{ business.miniDeliveryFee }}起送</span>
          <span class="mx-2">|</span>
          <span>¥{{ business.deliveryFees }}配送</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.business-list {
  background: #fff;
}

.business-item:last-child {
  border-bottom: none;
}
</style>